<template>
  <div class="news-detail-page">
    <div class="news-container">
      <el-card class="news-card" shadow="hover" v-loading="loading">
        <template v-if="!loading && news">
          <!-- 返回按钮 -->
          <div class="back-section">
            <el-button @click="$router.back()" :icon="ArrowLeft">返回</el-button>
          </div>

          <!-- 新闻标题 -->
          <div class="news-title-section">
            <h1 class="news-title">{{ news.title }}</h1>
            <div class="news-meta-top">
              <span class="meta-item">
                <el-icon><User /></el-icon>
                {{ news.author || '系统' }}
              </span>
              <span class="meta-item">
                <el-icon><Clock /></el-icon>
                {{ formatTime(news.publishTime) }}
              </span>
              <span class="meta-item">
                <el-icon><View /></el-icon>
                {{ news.views || 0 }} 次浏览
              </span>
            </div>
          </div>

          <!-- 标签和分类 -->
          <div class="news-tags-section">
            <el-tag :type="getCategoryType(news.categoryName)" v-if="news.categoryName">
              {{ news.categoryName }}
            </el-tag>
            <el-tag type="danger" v-if="news.isTop === 1">置顶</el-tag>
            <el-tag type="info" v-if="news.tags">{{ news.tags }}</el-tag>
            <el-tag type="info" v-if="news.source" effect="plain">{{ news.source }}</el-tag>
          </div>

          <!-- 副标题 -->
          <div class="news-subtitle" v-if="news.subtitle">
            {{ news.subtitle }}
          </div>

          <!-- 封面图 -->
          <div class="news-cover" v-if="news.coverImage">
            <img :src="news.coverImage" :alt="news.title" />
          </div>

          <!-- 多图展示 -->
          <div class="news-images" v-if="news.images && getImageList().length > 1">
            <div class="images-grid">
              <el-image 
                v-for="(img, index) in getImageList()" 
                :key="index"
                :src="img" 
                :alt="`${news.title} - 图片${index + 1}`"
                fit="cover"
                :preview-src-list="getImageList()"
                :initial-index="index"
                class="news-image-item"
              />
            </div>
          </div>

          <!-- 新闻内容 -->
          <div class="news-content">
            <div class="content-text" v-html="formatContent(news.content)"></div>
          </div>

          <!-- 底部信息 -->
          <div class="news-footer">
            <el-divider />
            <div class="footer-info">
              <div class="info-item">
                <span class="info-label">发布时间：</span>
                <span class="info-value">{{ formatTime(news.publishTime) }}</span>
              </div>
              <div class="info-item" v-if="news.updateTime && news.updateTime !== news.publishTime">
                <span class="info-label">更新时间：</span>
                <span class="info-value">{{ formatTime(news.updateTime) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">浏览次数：</span>
                <span class="info-value">{{ news.views || 0 }}</span>
              </div>
              <div class="info-item" v-if="news.likes !== undefined">
                <span class="info-label">点赞数：</span>
                <span class="info-value">{{ news.likes || 0 }}</span>
              </div>
            </div>
            <div class="footer-buttons">
              <el-button @click="$router.back()" :icon="ArrowLeft">返回</el-button>
              <el-button type="primary" @click="$router.push('/user/dashboard')" :icon="House">返回首页</el-button>
            </div>
          </div>
        </template>

        <el-empty v-else-if="!loading && !news" description="新闻不存在" :image-size="150">
          <el-button type="primary" @click="$router.back()">返回</el-button>
        </el-empty>
      </el-card>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { ArrowLeft, Clock, View, User, House } from '@element-plus/icons-vue';

export default {
  name: 'NewsDetail',
  components: {
    ArrowLeft,
    Clock,
    View,
    User,
    House
  },
  data() {
    return {
      loading: false,
      news: null
    };
  },
  async mounted() {
    await this.loadNewsDetail();
  },
  methods: {
    async loadNewsDetail() {
      this.loading = true;
      try {
        const newsId = this.$route.params.id;
        const res = await axios.get(`http://localhost:8080/api/news/detail/${newsId}`);
        
        if (res.data.code === 200) {
          this.news = res.data.data;
        } else {
          ElMessage.error(res.data.msg || '加载新闻详情失败');
        }
      } catch (error) {
        console.error('加载新闻详情失败:', error);
        ElMessage.error('加载新闻详情失败');
      } finally {
        this.loading = false;
      }
    },
    
    formatTime(time) {
      if (!time) return '-';
      try {
        const date = new Date(time.replace(' ', 'T'));
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        return time;
      }
    },
    
    getCategoryType(category) {
      const types = {
        '活动': 'success',
        '救助': 'warning',
        '招募': 'primary',
        '科技': 'info',
        '倡议': 'danger',
        '信息': 'primary'
      };
      return types[category] || 'primary';
    },
    
    getImageList() {
      if (!this.news || !this.news.images) return [];
      return this.news.images.split(',').filter(img => img.trim());
    },
    
    formatContent(content) {
      if (!content) return '<p>暂无内容</p>';
      return content
        .replace(/\n/g, '</p><p>')
        .replace(/^/, '<p>')
        .replace(/$/, '</p>');
    }
  }
};
</script>

<style scoped>
.news-detail-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.news-container {
  max-width: 1000px;
  margin: 0 auto;
}

.news-card {
  border-radius: 8px;
}

.news-card :deep(.el-card__body) {
  padding: 30px;
}

.back-section {
  margin-bottom: 20px;
}

/* 标题区域 */
.news-title-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.news-title {
  margin: 0 0 16px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1.5;
}

.news-meta-top {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
  font-size: 14px;
  color: #909399;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.meta-item .el-icon {
  font-size: 16px;
}

/* 标签区域 */
.news-tags-section {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

/* 副标题 */
.news-subtitle {
  font-size: 16px;
  color: #606266;
  margin-bottom: 24px;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

/* 封面图 */
.news-cover {
  margin-bottom: 24px;
  border-radius: 4px;
  overflow: hidden;
}

.news-cover img {
  width: 100%;
  height: auto;
  display: block;
  max-height: 500px;
  object-fit: cover;
}

/* 多图展示 */
.news-images {
  margin-bottom: 24px;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
}

.news-image-item {
  width: 100%;
  height: 200px;
  border-radius: 4px;
  overflow: hidden;
}

.news-image-item :deep(.el-image) {
  width: 100%;
  height: 100%;
}

/* 新闻内容 */
.news-content {
  margin-bottom: 30px;
}

.content-text {
  font-size: 16px;
  line-height: 1.8;
  color: #303133;
  word-wrap: break-word;
}

.content-text :deep(p) {
  margin: 0 0 16px 0;
  text-align: justify;
}

.content-text :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 20px 0;
  border-radius: 4px;
}

.content-text :deep(h1),
.content-text :deep(h2),
.content-text :deep(h3) {
  margin: 24px 0 16px 0;
  font-weight: 600;
  color: #303133;
}

.content-text :deep(h1) {
  font-size: 24px;
}

.content-text :deep(h2) {
  font-size: 20px;
}

.content-text :deep(h3) {
  font-size: 18px;
}

.content-text :deep(ul),
.content-text :deep(ol) {
  margin: 16px 0;
  padding-left: 30px;
}

.content-text :deep(li) {
  margin: 8px 0;
}

/* 底部信息 */
.news-footer {
  margin-top: 30px;
}

.footer-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 8px;
  font-size: 14px;
}

.info-label {
  color: #909399;
  margin-right: 8px;
}

.info-value {
  color: #606266;
}

.footer-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding-top: 20px;
}

/* 响应式 */
@media (max-width: 768px) {
  .news-detail-page {
    padding: 15px;
  }
  
  .news-card :deep(.el-card__body) {
    padding: 20px;
  }
  
  .news-title {
    font-size: 22px;
  }
  
  .news-meta-top {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .images-grid {
    grid-template-columns: 1fr;
  }
  
  .footer-buttons {
    flex-direction: column;
  }
  
  .footer-buttons .el-button {
    width: 100%;
  }
}
</style>
